<?php
/**
 * Created by PhpStorm.
 * User: fdg296
 * Date: 2017/8/14
 * Time: 11:22
 */
namespace backend\controllers;
use Yii;
use yii\web\AdminController;
use backend\models\GoodsSpec;
use backend\models\UploadForm;
use backend\models\GoodsSpecGroup;

class GoodsSpecController extends AdminController{
    public $layout = false;
    //业务关键字
    public $service = 'GoodsSpec';

    /**
     * 首页
     */
    public function actionIndex(){

        $where = ['use_flg'=>1];
        $list = GoodsSpecGroup::find()->where($where)->asArray()->all();
        $model = new UploadForm();
        $this->saveLog($this->service,'商品规格查询','VIEW', '');
        return $this->render('index',['list'=>$list,'model'=>$model]);
    }

    /**
     * 获取规格分组列表
     */
    public function actionGetSpecGroupList(){
        $data = Yii::$app->request->post();
        $condition = array();
        if(!empty($data['spec_group_name'])){
            $condition = ['like', 'spec_group_name', $data['spec_group_name']];
        }
        $query = GoodsSpecGroup::find()->where($condition);
        $count = $query->count();
        $sort_string = empty($data['columns'][$data['order'][0]['column']]['data']) ? 'id' : $data['columns'][$data['order'][0]['column']]['data'];
        $list = $query->offset($data['start'])->limit($data['length'])
            ->orderBy(array("$sort_string"=>$data['order'][0]['dir'] == 'asc' ? SORT_ASC : SORT_DESC))->all();
        if(empty($list)){
            $list = array();
        }

        //相关参数   http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        $this->saveLog($this->service,'商品规格查询','SEARCH', '查询参数'. "\r\n" .\yii\helpers\Json::encode($data));
        return \yii\helpers\Json::encode($result);
    }

    /**
     * 获取规格组详情
     */
    public function actionGetSpecGroupDetail(){
        $data = Yii::$app->request->post();

        $result = GoodsSpecGroup::findOne(array('id'=>$data['id']));
        return \yii\helpers\Json::encode($result);
    }
    
    /**
     * 新增规格组
     */
    public function actionAddSpecGroup(){
        $model = new GoodsSpecGroup();
        $data = Yii::$app->request->post();
        //del by allen.qiang 20171113 以下CHECK不需要，规格需要建N个规格组，以便在选择进可以按组快速切换显示 start
        //if (in_array($data['spec_type'], ['1','2'])){
        //    $spec_group = $model::find()->where('spec_type=:spec_type',[':spec_type'=>$data['spec_type']])->asArray()->one();
        //    if ($spec_group['id']){
        //        $this->retJson('规格组类型已存在，请选择其他规格组',500);
        //    }
        //}
        //del by allen.qiang 20171113 以下CHECK不需要，规格需要建N个规格组，以便在选择进可以按组快速切换显示 end
        if (!$data['spec_group_name']){
            $this->retJson('规格组名称必填',500);
        }
        $data_now['spec_group_name'] = trim($data['spec_group_name']);
        $data_now['spec_type'] = $data['spec_type'];
        $data_now['create_time'] = date('Y-m-d H:i:s',time());
        $data_now['creator'] = $model->getCreator();
        $data_now['use_flg'] = $data['use_flg'];
        $data_now['sort'] = empty($data['sort']) ? 1 : $data['sort'];;
        
        $res = Yii::$app->db->createCommand()->insert('j_goods_spec_group',$data_now)->execute();
        if($res > 0){
            $this->saveLog($this->service,'商品规格组新增','ADD',\yii\helpers\Json::encode($data_now));
            $this->retJson('品类组增加成功',200);
        }else{
            $this->retJson('品类组增加失败',500);
        }
    }

    /**
     * 修改规格
     */
    public function actionUpdateSpecGroup(){
        $model = new GoodsSpecGroup();
        $data = Yii::$app->request->post();
        if (!$data['spec_group_name']){
            $this->retJson('规格组名称必填',500);
        }
        //del by allen.qiang 20171113 以下CHECK不需要，规格需要建N个规格组，以便在选择进可以按组快速切换显示 start
        //if (in_array($data['spec_type'], ['1','2'])){
        //    $spec_group = $model::find()->where('spec_type=:spec_type',[':spec_type'=>$data['spec_type']])->asArray()->one();
        //    if ($spec_group['id'] && $spec_group['id'] != $data['id']){
        //        $this->retJson('规格组类型已存在，请选择其他规格组',500);
        //    }
        //}
        //del by allen.qiang 20171113 以下CHECK不需要，规格需要建N个规格组，以便在选择进可以按组快速切换显示 start
        $data_now['spec_group_name'] = trim($data['spec_group_name']);
        $data_now['spec_type'] = $data['spec_type'];
        $data_now['edit_time'] = date('Y-m-d H:i:s',time());
        $data_now['editor'] = $model->getCreator();
        $data_now['use_flg'] = $data['use_flg'];
        $data_now['sort'] = empty($data['sort']) ? 1 : $data['sort'];;
        
        $res = $model::updateAll($data_now, "id=:id",array(':id'=>$data['id']));
        if($res > 0){
            $this->saveLog($this->service,'商品规格组修改','MOD',\yii\helpers\Json::encode($data_now));
            $this->retJson('规格组修改成功',200);
        }else{
            $this->retJson('规格组修改失败',500);
        }
    }

    /**
     * 禁用规格组
     */
    public function actionDisableGroup(){
        $model = new GoodsSpecGroup();
        $data = Yii::$app->request->post();

        $mod_data['use_flg'] = 0;
        $mod_data['editor'] = $model->getCreator();
        $mod_data['edit_time'] = date('Y-m-d H:i:s',time());
        $res = $model::updateAll($mod_data, "id=:id",array(':id'=>$data['id']));

        if($res > 0){
            $this->saveLog($this->service,'禁用规格组','USEFLG0','ID = '.$data['id']);
            $this->retJson('规格组禁用成功',200);
        }else{
            $this->retJson('规格组禁用失败',500);
        }
    }

    /**
     * 启用规格组
     */
    public function actionEnableGroup(){
        $model = new GoodsSpecGroup();
        $data = Yii::$app->request->post();

        $mod_data['use_flg'] = 1;
        $mod_data['editor'] = $model->getCreator();
        $mod_data['edit_time'] = date('Y-m-d H:i:s',time());

        $res = $model::updateAll($mod_data, "id=:id",array(':id'=>$data['id']));

        if($res > 0){
            $this->saveLog($this->service,'启用规格组','USEFLG1','ID = '.$data['id']);
            $this->retJson('规格组启用成功',200);
        }else{
            $this->retJson('规格组启用失败',500);
        }
    }

    /**
     * 禁用规格
     */
    public function actionDisableSpec(){
        $model = new GoodsSpec();
        $data = Yii::$app->request->post();

        $mod_data['use_flg'] = 0;
        $mod_data['editor'] = $model->getCreator();
        $mod_data['edit_time'] = date('Y-m-d H:i:s',time());
        $res = $model::updateAll($mod_data, "id=:id",array(':id'=>$data['id']));

        if($res > 0){
            $this->saveLog($this->service,'禁用规格','USEFLG0','ID = '.$data['id']);
            $this->retJson('规格禁用成功',200);
        }else{
            $this->retJson('规格禁用失败',500);
        }
    }

    /**
     * 启用规格
     */
    public function actionEnableSpec(){
        $model = new GoodsSpec();
        $data = Yii::$app->request->post();

        $mod_data['use_flg'] = 1;
        $mod_data['editor'] = $model->getCreator();
        $mod_data['edit_time'] = date('Y-m-d H:i:s',time());

        $res = $model::updateAll($mod_data, "id=:id",array(':id'=>$data['id']));

        if($res > 0){
            $this->saveLog($this->service,'启用规格','USEFLG1','ID = '.$data['id']);
            $this->retJson('规格启用成功',200);
        }else{
            $this->retJson('规格启用失败',500);
        }
    }

    /**
     * 获取规格列表
     */
    public function actionGetSpecList(){
        $data = Yii::$app->request->post();
        $count = 0;
        $list = array();
        if(!empty($data['spec_group_id'])){

            if(!empty($data['spec_name'])){
                $condition = "spec_group_id = ".$data['spec_group_id']." and spec_name like '%".$data['spec_name']."%'";
                $where = array();
            }else{
                $condition = "spec_group_id=:spec_group_id";
                $where = array(':spec_group_id'=>$data['spec_group_id']);
            }
            $query = GoodsSpec::find()->where($condition,$where);
            $count = $query->count();
            $sort_string = empty($data['columns'][$data['order'][0]['column']]['data']) ? 'id' : $data['columns'][$data['order'][0]['column']]['data'];
            $list = $query->offset($data['start'])->limit($data['length'])
                ->orderBy(array("$sort_string"=>$data['order'][0]['dir'] == 'asc' ? SORT_ASC : SORT_DESC))->all();
            if(empty($list)){
                $list = array();
            }
        }

        //相关参数   http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        $this->saveLog($this->service,'获取规格列表','SEARCH',\yii\helpers\Json::encode($result));
        return \yii\helpers\Json::encode($result);
    }

    public function actionAddSpec(){
        $model = new GoodsSpec();

        //获取规格组
        $spec_group_list = array();
        $spec_group = GoodsSpecGroup::find()->select('id,spec_group_name')->asArray()->all();
        foreach($spec_group as $value){
            $spec_group_list[$value['id']]['spec_group_name'] = $value['spec_group_name'];
        }
        $data = Yii::$app->request->post();
        $spec_group_id = $data['spec_group_id'];
        if(!empty($data['spec_name']) && !empty($data['spec_val'])){
            $spec_name_list = $data['spec_name'];
            $spec_val_list = $data['spec_val'];
            $spec_sort_list = $data['add_spec_sort'];

            if(count($spec_name_list) != count($spec_val_list)){
                $this->retJson('规格和规格值不对应',500);
            }

            $spec_img_list = array();
            if(!empty($data['add_spec_img'])){
                $spec_img_list = $data['add_spec_img'];

                if(count($spec_val_list) != count($spec_img_list)){
                    $this->retJson('规格值和图片不对应',500);
                }
            }

            //删除数组中空的元素
            foreach($spec_name_list as $value){
                if(empty($value)){
                    /*$num = array_search($value,$spec_name_list);
                    array_splice($spec_name_list,$num,1);
                    array_splice($spec_val_list,$num,1);
                    array_splice($spec_sort_list,$num,1);
                    if(!empty($spec_img_list)){
                        array_splice($spec_img_list,$num,1);
                    }*/
                    $this->retJson('请删除空数据之后在提交',500);
                }
            }
            $spec_val_list = array_filter($spec_val_list);
            if (is_array($spec_val_list) && count($spec_val_list) > 0){
                $spec_val_list_new = array_unique($spec_val_list);
                if (count($spec_val_list_new) != count($spec_val_list)){
                    $this->retJson('填写的规格值不可重复，请查看',500);
                }
                $where[] = 'and';
                $where[] = ['spec_group_id'=>$spec_group_id];
                $where[] = ['in','spec_name',$spec_val_list_new];
                $find_goods_spec = GoodsSpec::find()->where($where)->asArray()->all();
                if (count($find_goods_spec) > 0){
                    $this->retJson('填写的规格值已存在',500);
                }
                foreach($spec_val_list as $value){
                    if(empty($value)){
                        $this->retJson('请删除空数据之后在提交',500);
                    }
                }
            }
        }else{
            $this->retJson('没有填写数据',500);
        }
        $transaction = Yii::$app->db->beginTransaction();
        try{
            $list = array();
            foreach($spec_name_list as $key=>$value){
                $list[] = [$value,$spec_group_id,$spec_group_list[$spec_group_id]['spec_group_name'],$spec_val_list[$key],
                    empty($spec_img_list) ? '' : $spec_img_list[$key],$spec_sort_list[$key],$model->getCreator(),date('Y-m-d H:i:s',time())];
            }
            $field_name = ['spec_name','spec_group_id','spec_group_name','spec_val','img_url','sort','creator','create_time'];
            $red = Yii::$app->db->createCommand()->batchInsert('j_goods_spec', $field_name, $list)->execute();
            if(!$red){
                throw new \Exception('操作失败');
            }
            $transaction->commit();
            $this->saveLog($this->service,'增加规规格','ADD','');
            $this->retJson('编辑成功',200);
        }catch (\Exception $e){
            $transaction->rollBack();
            //add by allen.qiang 20180112 异常处理，日志优化 start
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //add by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson($e->getMessage(),500);
        }
    }

    /**
     * 获取规格
     */
    public function actionGetSpecDetail(){
        $data = Yii::$app->request->post();

        $result = GoodsSpec::findOne(array('id'=>$data['id']));
        return \yii\helpers\Json::encode($result);
    }

    /**
     * 编辑规格
     */
    public function actionUpdateSpec(){
        $model = new GoodsSpec();
        $data = Yii::$app->request->post();

        $data_now['spec_group_id'] = $data['spec_group_id'];
        $data_now['spec_name'] = trim($data['spec_name']);
        $data_now['spec_val'] = trim($data['spec_val']);
        $data_now['img_url'] = trim($data['img_url']);
        $data_now['edit_time'] = date('Y-m-d H:i:s',time());
        $data_now['editor'] = $model->getCreator();
        $data_now['use_flg'] = $data['use_flg'];
        $data_now['sort'] = empty($data['sort']) ? 1 : $data['sort'];;

        $res = $model::updateAll($data_now, "id=:id",array(':id'=>$data['id']));
        if($res > 0){
            $this->saveLog($this->service,'规格修改','MOD',\yii\helpers\Json::encode($data_now));
            $this->retJson('规格修改成功',200);
        }else{
            $this->retJson('规格修改失败',500);
        }
    }
}